package org.treeleafj.fb;

import com.alibaba.fastjson.JSON;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by yaoshuhong on 2017/6/15.
 */
@RestController
@SpringBootApplication
public class Application {

    @RequestMapping("build")
    String build(String html, String data) throws IOException, TemplateException {

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_26);
        // 获取模板文件
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", html);
        cfg.setTemplateLoader(stringLoader);

        Template template = cfg.getTemplate("myTemplate", "utf-8");

        Map<String, Object> model = JSON.parseObject(data, Map.class);

        StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
